package com.gbx.qiushibaike.fragment;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.gbx.qiushibaike.R;
import com.gbx.qiushibaike.adapter.ItemAdapter;
import com.gbx.qiushibaike.application.BaseApplication;
import com.gbx.qiushibaike.entity.Entity;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class RecyclerFragment extends Fragment implements Callback<Entity>{
    public static final String  TAG = RecyclerFragment.class.getSimpleName();
    private ItemAdapter adapter;

    public RecyclerFragment() {

    }

    public static RecyclerFragment getInstance(String type) {
        RecyclerFragment fragment = new RecyclerFragment();
        Bundle bundle = new Bundle();
        bundle.putString("type",type);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_recycler,container,false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        String type = getArguments().getString("type");
        BaseApplication application = (BaseApplication) getActivity().getApplication();
        application.getService().getList(type, 1).enqueue(this);//这里需要enqueue为异步的,,而execute为同步
        RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recycler);
        adapter = new ItemAdapter(getContext());
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void onResponse(Call<Entity> call, Response<Entity> response) {
        adapter.addAll(response.body().getItems());
    }

    @Override
    public void onFailure(Call<Entity> call, Throwable t) {
        t.printStackTrace();
        Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
    }
}
